package com.aitaoxue.palx.ui;

import java.io.File;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.InjectView;

import com.aitaoxue.palx.AppContext;
import com.aitaoxue.palx.R;
import com.aitaoxue.palx.api.remote.AitaoXueApi;
import com.aitaoxue.palx.base.BaseActivity;
import com.loopj.android.http.AsyncHttpResponseHandler;

public class AboutActivity extends BaseActivity {

	@InjectView(R.id.new_icon)
	TextView newIcon;
	@InjectView(R.id.update_layout)
	RelativeLayout updateLayout;
	@InjectView(R.id.response_layout)
	RelativeLayout responseLayout;

	private String localAppPath;
	private DownloadManager downloadManager;

	@Override
	protected boolean hasBackButton() {
		return true;
	}

	@Override
	protected void onResume() {
		super.onResume();
		String newVersion = AppContext.getInstance().getProperty("new_version");
		if (newVersion != null && newVersion.equals("true")) {
			newIcon.setVisibility(View.VISIBLE);
		}
	}

	@Override
	protected int getActionBarTitle() {
		return R.string.about;
	}

	@Override
	protected int getLayoutId() {
		return R.layout.activity_about;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.update_layout:
			showWaitDialog();
			// 检测更新
			AitaoXueApi.AppUpdate(mUpdateHandler);
			newIcon.setVisibility(View.GONE);
			AppContext.getInstance().setProperty("new_version", "false");
			break;
		case R.id.response_layout:
			startActivity(new Intent(this, ResponseActivity.class));
			break;
		default:
			break;
		}
	}

	@Override
	public void initView() {
		updateLayout.setOnClickListener(this);
		responseLayout.setOnClickListener(this);
	}

	@Override
	public void initData() {

	}

	private AsyncHttpResponseHandler mUpdateHandler = new AsyncHttpResponseHandler() {

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
			String res = new String(arg2);

			try {
				JSONObject json = new JSONObject(res);
				String code = json.getString("code");
				if (code.equals("9998")) {
					// 有更新
					// 显示dialog
					AlertDialog.Builder builder = new AlertDialog.Builder(
							AboutActivity.this);
					View view = LayoutInflater.from(AboutActivity.this)
							.inflate(R.layout.dialog_update, null);
					builder.setView(view);
					Button positiveBotton = (Button) view
							.findViewById(R.id.btn_ok);
					Button negativeButton = (Button) view
							.findViewById(R.id.btn_cancel);

					final AlertDialog dialog = builder.create();
					dialog.show();

					positiveBotton.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View arg0) {
							dialog.dismiss();
							if (Environment.getExternalStorageState().equals(
									Environment.MEDIA_MOUNTED)) {
								Toast.makeText(AboutActivity.this,
										"正在更新,请在状态栏上查看详情", Toast.LENGTH_SHORT)
										.show();
								// 更新
								update();
							} else {
								Toast.makeText(AboutActivity.this, "请插入sd卡",
										Toast.LENGTH_SHORT).show();
							}

						}
					});

					negativeButton.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View arg0) {
							dialog.dismiss();
						}
					});
				} else if (code.equals("9997")) {
					// 没有更新
					Toast.makeText(AboutActivity.this, "已经是最新版本",
							Toast.LENGTH_SHORT).show();
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}

		}

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
				Throwable arg3) {

		}
	};

	private void update() {
		AppContext.getInstance().setProperty("new_version", "true");

		localAppPath = Environment.getExternalStorageDirectory()
				.getAbsolutePath() + "/download/aitaoxue_teacher.apk";
		File file = new File(localAppPath);
		if (file.exists()) {
			file.delete();
		}

		downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);

		// 更换
		String url = "https://sm.wdjcdn.com/release/files/jupiter/5.9.1.8951/wandoujia-wandoujia_web.apk";
		Uri source = Uri.parse(url);
		DownloadManager.Request request = new DownloadManager.Request(source);
		request.setAllowedNetworkTypes(Request.NETWORK_MOBILE
				| Request.NETWORK_WIFI);
		request.setAllowedOverRoaming(false);

		MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
		String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap
				.getFileExtensionFromUrl(url));
		request.setMimeType(mimeString);

		request.setShowRunningNotification(true);
		request.setVisibleInDownloadsUi(true);

		request.setDestinationInExternalPublicDir("/download",
				"aitaoxue_teacher.apk");
		request.setTitle("家教版下载中");

		long id = downloadManager.enqueue(request);

		AppContext.getInstance().setProperty("app_download_id",
				String.valueOf(id));

		registerReceiver(downloadReceiver, new IntentFilter(
				DownloadManager.ACTION_DOWNLOAD_COMPLETE));
	}

	private BroadcastReceiver downloadReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			long nowId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID,
					0l);
			if (Long.parseLong(AppContext.getInstance().getProperty(
					"app_download_id")) == nowId) {
				// 下载完成
				Toast.makeText(AboutActivity.this, "下载完成,即将安装",
						Toast.LENGTH_SHORT).show();

				// 安装
				Intent i = new Intent(Intent.ACTION_VIEW);
				String filePath = localAppPath;
				i.setDataAndType(Uri.parse("file://" + filePath),
						"application/vnd.android.package-archive");
				context.startActivity(i);
			}
		}
	};

}
